<template>
	<view>
		<!-- <back-fixed title="患者信息管理"></back-fixed> -->
		<view class="main">
			<sw-team :teamName="teamName" :singleTean="singleTean" v-show="!noTeam"></sw-team>
			<search-more @mySearch="mySearch" @navAction="navAction"></search-more>
			<nav-button @navSel="navSel" ref="navB" :navData="navList"></nav-button>

			<view class="list_box">
				<view class="list_top_tips">
					<view class="tips_left">
						{{filterTxt}}（{{totalCount}}）
					</view>
					<view class="flex row-between no_shrink" @click="MySync">
						<view class="p-r-16">同步</view>
						<view><u-image :src="flashIcon" width="32rpx" height="32rpx"></u-image></view>
					</view>
					<view class="tips_right">
						<view class="flex m-r-20" @click="upUserFilter" v-if="!noTeam">
							<view :class="{green:userList.length >0}">
								{{navUserSelectdText}}
							</view>
							<view class="m-l-20">
								<u-icon :name="showUser ?'arrow-up' : 'arrow-down'" size="32rpx"
									:color="userList.length >0 ?'#4DC0D9' : '#ccc'"></u-icon>
							</view>
						</view>
						<view class="flex" @click="upMarkFilter()">
							<view :class="{green:filterMarkList.length >0}">
								{{filterMarkList.length >0 ? '已选择标签' : '不限标签'}}
							</view>
							<view class="m-l-20">
								<u-icon :name="filterMark ?'arrow-up' : 'arrow-down'" size="32rpx"
									:color="filterMarkList.length >0 ?'#4DC0D9' : '#ccc'"></u-icon>
							</view>
						</view>
					</view>
				</view>
				<view style="padding-bottom: 80px;">
					<huanzhe-list ref="huanzheRef" :QueryParams="QueryParams" @myCount="myCount"
						@totalHuanzhe="totalHuanzhe" @dabiaoqian="dabiaoqian"
						:huanzheFlush="huanzheFlush"></huanzhe-list>
				</view>
			</view>
		</view>
		<u-popup v-model="showUser" border-radius="40" mode="top" :safe-area-inset-bottom="true" :mask-close-able="false">
			<huanzhe-team-list @close="Userconfirm" @confirm="Userconfirm" :mytype="form.typeCodeValue"
				ref="teamChild"></huanzhe-team-list>
		</u-popup>
		<u-popup v-model="showMark" border-radius="40" mode="top" :safe-area-inset-bottom="true" :mask-close-able="false">
			<mark-list @closeMark="closeMark" ref="markChild" @Markconfirm="Markconfirm"></mark-list>
		</u-popup>
		<u-popup v-model="filterMark" border-radius="40" mode="top" :safe-area-inset-bottom="true" :mask-close-able="false">
			<mark-list-filter @closeMark="filtercloseMark" @filtercloseMark="filtercloseMark" ref="filtermarkChild"
				@Markconfirm="filterMarkconfirm"></mark-list-filter>
		</u-popup>
		<con-me :show="conShow" @Pshow="Pshow"></con-me>
		<go-nav></go-nav>
	</view>
</template>

<script>
	import {
		getTeamByUser,
		editCustomerTag,
		tongbu
	} from '@/api/index.js'
	import {chooseTeamNow} from '@/utils/index.js'
	import teamList from './component/huanzhe-team-list/huanzhe-team-list.vue'
	export default {
		components: {
			'huanzhe-team-list':teamList
		},
		data() {
			return {
				conShow: false, //联系我们弹窗
				filterTxt: '全部', //全部|7天内新增|7天内流失  文字提示
				huanzheFlush: false, //刷新子组件患者列表
				QueryParams: {
					searchType: 0, //搜索类型 0：全部 1：新增患者 2：流失患者 3:我的患者
					searchValue: '', //搜索词
					tagIds: '',
					userIds: '',
					teamId: ''
				}, //查询携带的参数
				intoTeam: false,
				noTeam: false,
				singleTean: false,
				huanzheList: [],
				userList: [], //选中人员列表
				userSelectLength: 0,
				MarkList: [], //选中标签列表
				filterMarkList: [],
				AllFillterList: [], //回显选中标签
				MarkSelectLength: 0,
				filterMarkSelectLength: 0,
				showUser: false,
				showMark: false, //标签弹层
				filterMark: false, //标签弹层，筛选使用跟给人打标签数据隔离
				form: {
					typeCodeValue: 2 //1单 2多
				},
				totalCount: 0, //患者数量，全部旁边
				navList: [{
						name: '全部患者',
						unActive: false
					},
					{
						name: '新增患者',
						unActive: true
					},
					{
						name: '流失患者',
						unActive: true
					},
					{
						name: '我的患者',
						unActive: true
					},
				],
				flashIcon: require('@/static/icon/flash.png'),
				teamName: '',
				externalUserIdList: [], //批量患者打标签所选中的人员名单，externalUserId
				editTagIdList: [], //批量标签选择，两个都不能为空
				firstInMarkFlag: false, //过滤标签只有第一次才拉起请求
				firstInUserFlag: false //添加入过滤只有第一次才拉起请求
			}
		},
		onShow() {
			this.init()
			uni.removeStorageSync('patientDetails')  //清空患者管理详情的暂存数据
		},
		computed: {
			navUserSelectdText() {
				if (this.userList.length == this.userSelectLength) { //全选
					return '全部添加人'
				}
				if (this.userList.length > 0) {
					return '已选添加人'
				} else {
					return '全部添加人'
				}
			}
		},
		onLoad() {},
		onReachBottom() {
			 console.log(123123);
			 //当前条目数
			// console.log(this.$refs.huanzheRef.pageNum);
			if(this.$refs.huanzheRef.pageNum > 1){
				this.$refs.huanzheRef.getTeam()
				//console.log(this.$refs.huanzheRef.list);
			}
		},
		methods: {
			async MySync() {
				let res = await tongbu()
				uni.showLoading({
					title: "加载数据中"
				})
				if (res.code == 200) {
					setTimeout(() => {
						this.$u.toast('同步存量患者成功！')
						this.$refs.huanzheRef.clearPageStatus()
						this.$refs.huanzheRef.getTeam()
						uni.hideLoading()
					}, 5000)

				} else {
					setTimeout(() => {
						this.$u.toast('同步存量患者失败！')
						uni.hideLoading()
					}, 5000)

				}
				//console.log(res);
			},
			async init() {
				await this.getTeamList() //仅判断是否有团队，所以分页不分页无所谓了
				await this.hasTeamInit()
				if (!this.noTeam) { //有团队才去请求接口
					this.$nextTick(() => {
						//console.log(this.$refs,'111');
						//this.$refs.teamChild.clearPageStatus() //切换团队要清除团队成员信息
						//this.$refs.teamChild.getTeam() //每次进入页面后,都要初始化团队列表
						// uni.$emit('huanTListClear')
						// uni.$emit('huanTList')
					})
				}
			},
			async hasTeamInit() {
				await chooseTeamNow()
				let res = uni.getStorageSync('myTeam')
				if (res && res?.code == 200) {
					this.teamName = res.data.name
				}else{
					this.noTeam = true
				}
				if(this.navList.length == 3){
					this.QueryParams.userIds = uni.getStorageSync('userinfo').user.userId
				}
				if (this.noTeam && this.navList.length == 4) { //没有团队的情况下，传值传userid
					this.QueryParams.userIds = uni.getStorageSync('userinfo').user.userId
					this.navList.pop() //没有团队就隐藏我的团长navbar
				} else {
					//console.log(uni.getStorageSync('myTeam').data.id,'teamid');
					// if(!uni.getStorageSync('myTeam')){
					// 	uni.redirectTo({
					// 		url:'/pages/patient/switchTeam'
					// 	})
					// }
					if (uni.getStorageSync('myTeam')) {
						//console.log(1221);
						this.QueryParams.teamId = uni.getStorageSync('myTeam').data.id
					}

				}
			},
			upUserFilter() {
				this.showUser = true
				// if(!this.firstInUserFlag){
				// 	this.$refs.teamChild.$emit('startRequest')  //只有点击过滤标签列表，拉起页面才去请求接口
				// 	this.firstInUserFlag = true
				// }
				this.$nextTick(() => {
					this.$refs.teamChild.clearPageStatus()
					this.$refs.teamChild.getTeam()
				})
			},
			upMarkFilter() {
				this.filterMark = true
					this.$nextTick(() => {
						this.$refs.filtermarkChild.$emit('startRequest') //只有点击过滤标签列表，拉起页面才去请求接口
						this.firstInMarkFlag = true
					})
			},
			async getTeamList() { //仅判断是否有团队，所以分页不分页无所谓了
				let res = await getTeamByUser({
					pageNum: 1,
					pageSize: 15
				})
				if (res.code == 200) {
					// if (!this.teamName && res.rows.length !== 0) {
					// 	uni.redirectTo({
					// 		url: '/pages/patient/switchTeam'
					// 	})
					// }
					if (res.rows.length == 0) {
						this.noTeam = true
						//console.log(this.noTeam,'lll');
					} else {
						if (res.rows.length == 1) {
							this.singleTean = true
						}
					}
				}
				//console.log(res);
			},
			closeMark(val) {
				this.MarkList = val //打标签选中标签  
				this.showMark = false
			},
			filtercloseMark(val) {
				this.filterMarkList = [] //过滤选中标签
				//this.postMark()
				// this.$refs.huanzheRef.clearPageStatus()
				// this.$refs.huanzheRef.getTeam()
				this.QueryParams.tagIds = ''
				this.filterMark = false
			},
			Markconfirm(list) {
				if (list.markChoose.length == 0) {
					this.$u.toast('至少应选择一个标签')
					return
				}
				this.editTagIdList = []
				this.MarkList = this.$u.deepClone(list.markChoose) //打标签选中标签

				this.MarkSelectLength = list.list.length //总长度
				this.MarkList.map(v => {
					this.editTagIdList.push(v.tagId)
				})
				this.huanzheFlush = false
				this.postMark()
			},
			filterMarkconfirm(list) {
				this.filterMarkList = this.$u.deepClone(list.markChoose) //过滤选择标签
				this.AllFillterList = this.$u.deepClone(list.list)
				this.filterMarkSelectLength = list.list.length //总长度
				if (this.filterMarkList.length > 0) {
					const arr = []
					this.filterMarkList.map(v => arr.push(v.tagId))
					//this.QueryParams.searchType = '' //有了查询条件，searchType就不能为全部了
					this.QueryParams.tagIds = arr
					//console.log(this.QueryParams.tagIds,'tagids');
				} else {
					//this.QueryParams.searchType = '' //有了查询条件，searchType就不能为全部了
					this.QueryParams.tagIds = null //这里写null是因为子组件watch值需要改变才能触发，传了null会被请求方法过滤掉。没传等于默认所有
				}
				this.filterMark = false
				//console.log(list,'Markconfirm');
			},
			async postMark() {
				const params = {
					'editTagIdList': this.editTagIdList,
					'externalUserIdList': this.externalUserIdList,
					'flag': 'multi'
				}
				// console.log();
				//console.log(bb);
				let res = await editCustomerTag(params)
				if (res.code == 200) {
					this.resetMarkRes()
					//this.$refs.huanzheRef.clearPageStatus()
					//this.$refs.huanzheRef.getTeam()
				}
			},
			resetMarkRes() { //重置所有患者列表打标签的动作
				this.$store.commit('PATIENTSHOW', false) //关闭患者选择圆圈
				this.huanzheList.forEach(v => {
					v.check = false
				})
				this.huanzheFlush = true //重新请求一下患者列表
				this.$refs.huanzheRef.huanzheList = [] //所选患者为空，子组件
				this.$refs.markChild.markChoose = [] //所选标签传值置空，子组件
				this.$refs.markChild.list.forEach(v => { //所选标签置空，子组件。跟上面有区别。上面是重置emit传值，这里重置了子组件本身的选值
					v.tagList.forEach(val => val.check = false)
				})
				this.editTagIdList = []
				this.externalUserIdList = []
				this.MarkList = []
				this.MarkSelectLength = 0
				this.showMark = false //成功后关闭标签列表
			},

			// closeUser(val) { //人员弹层X关闭
			// 	this.userList = val //选中人员   g改
			// 	this.showUser = false
			// },
			Userconfirm(list) {
				console.log(this.userSelectLength, this.userList.length);
				const arr = this.$u.deepClone(list)
				this.userSelectLength = list.length
				this.userList = arr.filter(v => v.check == true) //选中人员
				if (this.userSelectLength !== this.userList.length &&
					this.userList.length > 0) {
					const arr = []
					//this.QueryParams.searchType = '' //有了查询条件，searchType就不能为全部了
					this.userList.map(v => arr.push(v.userId))
					this.QueryParams.userIds = arr

				} else if (this.userList.length == 1) { //只有一条的情况下
					const arr = []
					this.userList.map(v => arr.push(v.userId))
					this.QueryParams.userIds = arr

				} else {
					//this.QueryParams.searchType = '' //有了查询条件，searchType就不能为全部了
					this.QueryParams.userIds = null //这里写null是因为子组件watch值需要改变才能触发，传了null会被请求方法过滤掉。没传等于默认所有
				}


				this.showUser = false
			},
			navSel(obj) { //导航切换
				// this.$refs.huanzheRef.clearPageStatus()
				// this.$refs.huanzheRef.list = []

				//this.huanzheFlush = true
				if (obj.name == "全部患者") { //搜索类型 0：全部 1：新增患者 2：流失患者 3:我的患者
					this.QueryParams['searchType'] = 0
					this.filterTxt = '全部'
				}
				if (obj.name == "新增患者") {
					this.QueryParams['searchType'] = 1
					this.filterTxt = '7天内新增'
				}
				if (obj.name == "流失患者") {
					this.QueryParams['searchType'] = 2
					this.filterTxt = '7天内流失'
				}
				if (obj.name == "我的患者") {
					this.QueryParams['searchType'] = 3
					this.filterTxt = '我的'
				}
				//this.huanzheFlush = false
				//this.$refs.huanzheRef.reset()
				//console.log(this.$refs.huanzheRef.list, this.huanzheList);
			},
			mySearch(val) { //搜索词
				this.$u.debounce(() => this.QueryParams['searchValue'] = val, 500) //防抖加搜索赋值，传递给子组件患者。子组件拿到后用watch方法重新加载页面
			},
			totalHuanzhe(num) {
				this.totalCount = num
			},
			myCount(val) {
				this.huanzheList = val
			},
			navAction(val) { //搜索右侧批量动作
				this.huanzheFlush = false //重新请求一下患者列表,这里把flush先默认false，以便进去后能监控到flush的变化
				if (val == '批量打标签') { //批量打标签只能选自己的客户
					//console.log(this.$refs.navB.navList.length,1233);
					if (this.$refs.navB.navList && this.$refs.navB.navList.length == 3) { //未加入团队
						//this.$u.toast('未加入团队不能批量打标签')
						//return
						// this.$refs.navB.navList.forEach(v => v.unActive = true) //患者导航的选中效果清除
						// this.$refs.navB.navList[3].unActive = false //选到我的患者里面				
					} else {
						//console.log(this.$refs.navB);
						this.$refs.navB.navList.forEach(v => v.unActive = true) //患者导航的选中效果清除
						this.$refs.navB.navList[3].unActive = false //选到我的患者里面
						this.QueryParams['searchType'] = 3
					}
					this.$store.commit('PATIENTSHOW', true)
				}
				if (val == '批量导出') {
					this.conShow = true
					//this.$u.toast('暂未开放')
				}
				//console.log(val);
			},
			dabiaoqian(list) { //打标签button，huanzhe-list组件
				//console.log(list);
				if (this.huanzheList.every(v => v.check == false)) {
					this.$u.toast('至少选择一名患者才能打标签')
					return
				}
				this.showMark = true
				this.$nextTick(() => {
					this.$refs.markChild.$emit('startRequest') //只有在患者打标签时，拉起页面才去请求接口
				})
				this.externalUserIdList = []
				this.huanzheList.map(v => { //弹出标签列表之前，把人员的id收集起来
					if (v.check) {
						this.externalUserIdList.push(v.externalUserId)
					}
				})

			},
			Pshow(val) {
				this.conShow = false
			},
		},
		beforeDestroy() {
			this.$store.commit('FilterChoose',[])
			this.$store.commit('PATIENTSHOW', false)
			this.$store.commit('FilterTeamChoose', [])
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		//	padding-top: 60rpx;
		background-color: #F8F8F8;
		//width: 375px; //加
		//margin: 0 auto; //加
		//position: relative;
		//min-height: 100vh;

		.list_box {
			background-color: #F8F8F8;
			//	padding-top: 50px;
			//position: absolute;
			width: 100%;
			min-height: 100vh;

			.list_top_tips {
				display: flex;
				align-items: center;
				padding: 20rpx 24rpx 24rpx 24rpx;
				justify-content: space-between;
				// position: fixed;
				// z-index: 2;
				background-color: #f8f8f8;
				width: 100%;

				.tips_left {
					font-weight: 500;
					font-size: 28rpx;
					color: #666666;
					line-height: 33rpx;
				}

				.tips_right {
					display: flex;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					line-height: 33rpx;
					flex-shrink: 0;
				}
			}
		}
	}

	.my_fixed {
		//position: fixed;
		//z-index: 2;
		width: 100%;
		//top: 48px;
	}
	.no_shrink{
		flex-shrink: 0;
	}
	.green {
		color: #4DC0D9 !important;
	}
</style>